// ==UserScript==
// @name         aliyun导出监控数据
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  try to take over the world!
// @author       xuke
// @match        https://cloudmonitor.console.aliyun.com
// @include      https://cloudmonitor.console.aliyun.com/*
// @updateURL    https://gitee.com/pandora/install/raw/master/aliyun_mon.js
// @grant        none
// ==/UserScript==

// 主机监控地址 https://cloudmonitor.console.aliyun.com/?spm=5176.100251.aliyun_sidebar.aliyun_sidebar_cms.6f9a4f15AxoVVM#/hostmonitor/host

let csrf = ALIYUN_CONSOLE_CONFIG.SEC_TOKEN

async function aliyun_getvalue(ins, metric){
    let time_end = new Date().getTime()
    let time_start = time_end-86400000
    let ins_str = JSON.stringify(ins)
    let url = `https://cloudmonitor.console.aliyun.com/metrics/getLast.json?&csrf_token=${csrf}&dimensions=${ins_str}&endTime=${time_end}&metric=${metric}&namespace=acs_ecs_dashboard&startTime=${time_start}`
    let r = await fetch(url)
    return await r.json()
}

async function aliyun_getHosts(){
    var r = await fetch(`https://cloudmonitor.console.aliyun.com/host/getHostList.json?__preventCache=1561173122276&csrf_token=${csrf}&pageSize=200`)
    let j = await r.json()
    let hosts = j.data
    hosts.forEach(e=>{
        let s = e.ipGroup.split(',')
        s = s.filter(x=>x.indexOf('172')!=0)
        e.ipGroup = s.join(',')
    })
    console.log(hosts)
    return hosts
  }

async function aliyun_main(){
    await init_btn()
}

function aliyun_merge(hosts, s, metric, shortm){
    hosts.forEach(e=>{
        let v = s.filter(x=>x.instanceId==e.instanceId)[0]
        if(!v) return
        ['Average', 'Maximum', 'Minimum', 'V'].forEach(attr=>{
            if(v[attr]!=null){  // v[attr] may is 0
                e[shortm+'_'+attr] = v[attr]
            }
        })
    })
}

function aliyun_merge_disk(hosts, s, metric, shortm){
    hosts.forEach(e=>{
        let v = s.filter(x=>x.instanceId==e.instanceId)
        if(!v[0]) return
        let dv = '', sum=0
        v.forEach(x=>{
            dv += `${x.device}:${x.Average} `
            sum += x.Average
        })
        e['disk_total']=dv
        e['disk_v']= sum
    })
}

var objectToCSVRow = function(o) {
    let r = []
    let ks = Object.keys(o[0])
    ks = ks.filter(x=>['aliUid', 'aliyunHost', 'operatingSystem', 'region', 'serialNumber',
        'tianjimonVersion', 'networkType', 'instanceTypeFamily'].indexOf(x)<0)
    r.push(ks.join(','))
    o.forEach(e=>{
        if(!e.cpu_Average) return
        let s = ks.map(k=>{
            let v = e[k]
            if(typeof(v)=='string'){
                v = v.replace(/\,/g, '-')
                v = v.replace(/"/g, '""')
            }
            return v.toString()
        })
        s.join(',')
        r.push(s)
    })
    return r.join('\r\n');
}

var exportToCSV = function(csvContent) {
    var encodedUri =  encodeURI('data:text/csv;charset=utf-8,' + csvContent)
    var link = document.createElement("a")
    link.setAttribute("href", encodedUri)
    link.setAttribute("download", "ali_mon_report.csv")
    document.body.appendChild(link) // Required for FF
    link.click()
    document.body.removeChild(link)
}

async function aliyun_export(){
    let hosts = await aliyun_getHosts()
    let hs = hosts.map(x => { return {"instanceId":x.instanceId } })
//    console.log(hs)
    let x
    x = await aliyun_getvalue(hs, 'cpu_total')
    aliyun_merge(hosts, x.data, 'cpu_total', 'cpu')

    x = await aliyun_getvalue(hs, 'memory_usedutilization')
    aliyun_merge(hosts, x.data, 'memory_usedutilization', 'mem')

    x = await aliyun_getvalue(hs, 'diskusage_utilization')
 //   console.log(x.data[0])
    aliyun_merge_disk(hosts, x.data)

//    console.log(hosts)

    exportToCSV(objectToCSVRow(hosts))

}

async function init_btn(){
    let str = `<button alarm-command=""  product="'ecs'" class="btn btn-default  ng-binding" aliyun-console-spm=""  data-spm-click="gostr=">导出</button>`
    let btns =  $('button').filter((_, v)=>v.getAttribute('type')=='submit')
    let btn = $(str).get(0)
    btns[0].parentNode.appendChild(btn)
    btn.addEventListener('click', async ()=>{
        await aliyun_export()
    })
}

(function() {
    'use strict';
    if(document.URL.indexOf('/hostmonitor/host')==-1) return
    if(!ALIYUN_CONSOLE_CONFIG) return
    setTimeout(aliyun_main, 100)


    // Your code here...
})();


